﻿using System;
using System.Threading;
using System.Windows.Threading;
using Common;
using Microsoft.ServiceBus;
using Microsoft.ServiceBus.Messaging;

namespace OnlineStoreSystem
{
    public partial class MainWindow
    {
        private ServiceBus<ItemCreated> _bus = new ServiceBus<ItemCreated>("catalog", "onlinestore");

        public MainWindow()
        {
            InitializeComponent();

            var viewModel = new MainViewModel();
            DataContext = viewModel;

            _bus.AddHandler(i =>
                                {
                                    var item = new OrderItem
                                    {
                                        Name = i.Name,
                                        Price = i.Price
                                    };

                                    Dispatcher.BeginInvoke(new Action(() => viewModel.Items.Add(item)));
                                });
            _bus.Start();
        }

        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            _bus.Stop();
            base.OnClosing(e);
        }

        //private void OnStart()
        //{
        //    ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.Http;

        //    var client = SubscriptionClient.Create("catalog", "onlinestore");

        //    while (true)
        //    {
        //        var message = client.Receive(TimeSpan.FromSeconds(5));
        //        if (message != null)
        //        {
        //            var body = message.GetBody<ItemCreated>();
        //            var item = new OrderItem
        //            {
        //                Name = body.Name,
        //                Price = body.Price
        //            };

                    
        //            message.Complete();
        //        }
        //        Thread.Sleep(1000);
        //    }
        //}
    }
}
